import "cropperjs/dist/cropper.css";
import { Button, Col, Modal, Row, Slider } from 'antd';
import Cropper from "react-cropper";
import { useIntl } from 'umi';
import React, { useEffect, useState } from 'react';
import { RedoOutlined, UndoOutlined } from "@ant-design/icons";

interface ImageCropperProps {
    modalVisible?: boolean;
    originFile: File;
    autoCropper?: boolean;
    cropperProps?: Cropper.Options;
    onComplete: (result: File) => void;
    onCancel: () => void;
}

const ImageCropper: React.FC<ImageCropperProps> = (props) => {
    const { modalVisible, originFile, autoCropper, cropperProps, onComplete, onCancel } = props;

    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();

    const [cropperSrc, setCropperSrc] = useState<any>();
    const [cropper, setCropper] = useState<any>();
    const [currentRotate, setCurrentRotate] = useState(0);

    /**
     * 将File对象转换为DataUrl
     * @param file 要转换的File对象
     * @returns 
     */
    const fileTransformDataURL = async (file: File) => {
        const src = await new Promise(resolve => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
        });

        return src;
    }

    /**
     * 旋转角度变化处理逻辑
     * @param value 
     */
    const rotateChangeHandle = (value: number) => {
        cropper.rotateTo(value);
        setCurrentRotate(value);
    }

    const finishHandle = () => {
        const canvas = cropper.getCroppedCanvas();
        const { name, type } = originFile;

        // 将编辑完成后的图转换为File类型
        canvas.toBlob(async (blob: any) => {
            const cropperResultFile = new File([blob], name, { type: type || "image/png" });
            // 触发完成事件
            onComplete(cropperResultFile);
        });
    }

    // 当 originFile 发生变化时更新cropperSrc
    useEffect(() => {

        async function getDataURL() {
            const src = await fileTransformDataURL(originFile);
            setCropperSrc(src);
        }

        if (modalVisible) {
            getDataURL()
        }
    }, [originFile, modalVisible]);

    const cropperRender = (extendProps?: Cropper.Options) => {
        return <Cropper
            style={{ height: 400, width: "100%" }}
            initialAspectRatio={1}
            src={cropperSrc}
            viewMode={1}
            minCropBoxHeight={110}
            minCropBoxWidth={110}
            background={true}
            responsive={true}
            checkOrientation={false}
            autoCropArea={1}
            onInitialized={(instance: any) => {
                setCropper(instance);
            }}
            guides={true}
            cropBoxResizable={false}
            {...cropperProps}
            {...extendProps}
        />
    };

    return (
        <>
            {autoCropper && cropperRender({
                crop: finishHandle
            })}
            {!autoCropper && <Modal title={intl.formatMessage({
                id: 'component.imagecropper.modal.title',
                defaultMessage: '编辑图片'
            })}
                visible={modalVisible}
                maskClosable={false}
                onOk={finishHandle}
                onCancel={onCancel}
                destroyOnClose>
                {cropperRender()}
                <Row style={{
                    margin: "20px 60px 0 60px",
                }}>
                    <Col>
                        <Button type="text" icon={<UndoOutlined rotate={170} />} shape="circle" onClick={() => rotateChangeHandle((currentRotate - 1))} />
                    </Col>
                    <Col flex="auto">
                        <Slider max={180} min={-180}
                            onChange={rotateChangeHandle}
                            value={currentRotate}
                            tooltipVisible />
                    </Col>
                    <Col>
                        <Button type="text" icon={<RedoOutlined rotate={-170} style={{ fontSize: 16 }} />} shape="circle" onClick={() => rotateChangeHandle((currentRotate + 1))} />
                    </Col>
                </Row>
            </Modal>}
        </>
    );
}

export default ImageCropper;